layui.use(['element', 'jquery', 'table', 'form', 'laytpl', 'cmcookie', 'cmrouter', 'cmwindow', 'sysMenu', 'sysMenuPower'], function() {
	var cmwindow = layui.cmwindow,
		$ = layui.$,
		form = layui.form,
		laytpl = layui.laytpl,
		table = layui.table,
		sysMenu = layui.sysMenu,
		sysMenuPower = layui.sysMenuPower,
		cmcookie = layui.cmcookie,
		cmrouter = layui.cmrouter;

	var elms = {
		noDataTips: $('#nodata_tips'),
		oDucument: $(document),
		oMain: $('#main'),
		tplMainAuth: $('#main_auth')
	};

	var datas = {
		selectedMenu: null,
		tableCurrentPage: 1,
		authTable: null
	};

	var methods = {
		// 初始化树
		initMenuTree: function() {
			var that = this;
			sysMenu.getTreeForAdmin()
			.then(function(resp) {

				if (resp && resp.success) {
					if (resp.data) {
						elms.noDataTips.hide();
						$('#menu_tree').tree({
							data: resp.data,
							lines: true,
							formatter: function(node){
								return node.name;
							},
							onSelect: function(e){
								if(!datas.selectedMenu || e.id !== datas.selectedMenu.id){
									datas.selectedMenu = e;
									that.initMainAuth(e.menuKey);
									/* if($('#menu_tree').tree('isLeaf',e.target)){
										
									}else{
										elms.oMain.empty();
										datas.authTable = null;
									}	 */
								}
							}
						});
						// 删除tree图标
						that.delTreeIcon();
					}
				}
			})
			.fail(function(error) { });
		},
		delTreeIcon: function(){
			$('#menu_tree').find("span.tree-icon").removeClass('tree-folder tree-file');
		},
		// 添加菜单
		addMenu: function(type) {

			var selectedNode = $('#menu_tree').tree('getSelected'),
				detailUrl = cmrouter.path.menu.detail() + "?_optype=add";
			
			if(type==='addSubTreeNode'){
				if(!selectedNode){
					cmwindow.msg("请先选择菜单");
					return;
				}
				detailUrl += "&id=" + selectedNode.menuKey;
			}

			cmwindow.open({
				title: "添加菜单",
				type: 2,
				skin: 'wt-layer', //样式类名
				area: ['600px', '440px'],
				closeBtn: 1, //不显示关闭按钮
				content: detailUrl
			});
		},
		// 编辑菜单
		editMenu: function() {
			
			var selectedNode = $('#menu_tree').tree('getSelected'),
				id = '';
			if(selectedNode){
				id = selectedNode.id;
			}
			
			if ($.type(id) !== 'string' || id === '') {
				cmwindow.msg("操作失败");
				return;
			}
			
			cmwindow.open({
				title: "编辑菜单",
				type: 2,
				skin: 'wt-layer', //样式类名
				area: ['600px', '400px'],
				closeBtn: 1, //不显示关闭按钮
				content: cmrouter.path.menu.detail() + "?id=" + id + "&_optype=edit"
			});
		},
		// 删除菜单
		delMenu: function(){
			var selectedNode = $('#menu_tree').tree('getSelected'),
				id = '';
			if(selectedNode){
				id = selectedNode.id;
			}
			
			if ($.type(id) !== 'string' || id === '') {
				cmwindow.msg('删除操作失败');
				return;
			}
			
			cmwindow.confirm('确定删除吗？', function(index) {
			
				sysMenu.deleteMenu({
						data: {
							"id": id
						}
					})
					.then(function(resp) {
						cmwindow.msg(resp.msg, {
							time: 3000
						});
						if (resp.success && resp.code === 200) {
							cmwindow.updateTabPage();
						}
					})
					.fail(function(error) {
						cmwindow.msg("删除失败", {
							time: 3000
						});
					});
			
				cmwindow.close(index);
			}); 
		},
		// 初始化菜单权限
		initMainAuth: function(menuKey){
			
			if(datas.authTable){
				table.reload('authTable', {
					where: {
						"_rd": new Date().getTime(),
						"menuKey": menuKey
					},
					page: {
						curr: 1 
					}
				});
			}else{
				
				laytpl(elms.tplMainAuth.html()).render({}, function(html) {
					elms.oMain.html(html);
				});
				
				datas.authTable = table.render({
					elem: '#authTable',
					url: sysMenuPower.getListByMenuKey(),
					height: 'full-20',
					where: {
						"_rd": new Date().getTime(),
						"menuKey": menuKey
					},
					headers: {
						'loginusertoken': cmcookie.get('loginusertoken')
					},
					id: 'authTable',
					page: false,
					loading: true,
					toolbar: "#toolbar",
					defaultToolbar: ['filter'],
					cols: [
						[{
							field: 'powerKey',
							title: '键',
							width: 200
						}, {
							field: 'menuKey',
							title: '关联菜单键名'
				
						}, {
							field: 'name',
							title: '名称'
				
						}, {
							field: 'url',
							title: '路由地址'
				
						}, {
							fixed: 'right',
							title: '操作',
							toolbar: '#rowbar',
							width: 200
						}]
					],
					response: {
						statusCode: 200,
						countName: 'total'
					},
					request: {
						pageName: 'pageNo',
						limitName: 'pageSize'
					},
					parseData: function(res) { //res 即为原始返回的数据
						return {
							"code": res.code, //解析接口状态
							"msg": res.msg, //解析提示文本
							"total": res.total, //解析数据长度
							"data": res.data //解析数据列表
						};
					},
					done: function(res, curr, count) {
						// 设置当前页码
						datas.tableCurrentPage = curr;
					}
				});
				
				
			}
			
			
		},
		// 添加菜单权限
		addMenuAuth: function(){
			
			console.log(datas.selectedMenu);
			
			cmwindow.open({
				title: "添加菜单权限",
				type: 2,
				skin: 'wt-layer', //样式类名
				area: ['600px', '340px'],
				closeBtn: 1, //不显示关闭按钮
				content: cmrouter.path.menu.authDetail() + "?_optype=add&id=" + datas.selectedMenu.menuKey
			});
		},
		// 删除菜单权限
		delMenuAuthById: function(id) {
			if ($.type(id) !== 'string' || id === '') {
				cmwindow.msg('删除操作失败');
				return;
			}
		
			cmwindow.confirm('确定删除吗？', function(index) {
		
				sysMenuPower.delMenuPower({
					data: {
						"id": id
					}
				})
				.then(function(resp) {
					cmwindow.msg(resp.msg, {
						time: 2000
					});
					if (resp.success && resp.code === 200) {
						cmwindow.updateTabTable('authTable', datas.tableCurrentPage);
					}
				})
				.fail(function(error) {
					cmwindow.msg("删除失败", {
						time: 2000
					});
				});
		
				cmwindow.close(index);
			});
		},
		// 编辑菜单权限
		editMenuAuthById: function(id){
			if ($.type(id) !== 'string' || id === '') {
				cmwindow.msg("操作失败");
				return;
			}
			
			cmwindow.open({
				title: "编辑菜单权限",
				type: 2,
				skin: 'wt-layer', //样式类名
				area: ['600px', '340px'],
				closeBtn: 1, //不显示关闭按钮
				content: cmrouter.path.menu.authDetail() + "?_optype=edit&id=" + id
			});
		}
	};

	methods.initMenuTree();
	
	/**
	 * 事件处理
	 */
	// 新增一级菜单
	elms.oDucument.on('click', '#addPTreeNode', function(ev) {
		methods.addMenu();
		ev.stopPropagation();
	});
	
	// 新增子级菜单
	elms.oDucument.on('click', '#addSTreeNode', function(ev) {
		methods.addMenu('addSubTreeNode');
		ev.stopPropagation();
	});
	
	// 编辑
	elms.oDucument.on('click', '#editTreeNode', function(ev) {
		methods.editMenu();
		ev.stopPropagation();
	});
	
	// 删除
	elms.oDucument.on('click', '#delTreeNode', function(ev) {
		methods.delMenu();
		ev.stopPropagation();
	});
	
	/**
	 * select数据表格row操作列
	 */
	table.on('tool(authTable)', function(obj) {
		var data = obj.data,
			layEvent = obj.event,
			tr = obj.tr;
		
		if (layEvent === 'detail') {
	
		} else if (layEvent === 'del') {
			methods.delMenuAuthById(data.id);
		} else if (layEvent === 'edit') {
			methods.editMenuAuthById(data.id);
		}
	});
	
	/**
	 * select数据表格工具条
	 */
	table.on('toolbar(authTable)', function(obj) {
	
		var checkStatus = table.checkStatus('authTable'),
			size = checkStatus.data.length;
		checkData = checkStatus.data,
			res = [];
	
		for (var i = 0; i < size; i++) {
			res.push(checkData[i].id);
		}
	
		switch (obj.event) {
			case 'add':
				methods.addMenuAuth();
				break;
		};
	});
	
	// 拖拉改变div窗口时要用到
	$("#main").resize(function(){});
	
});
